package com.sxj.PDMS.controller.admin;

import com.sxj.PDMS.common.BaseResponse;
import com.sxj.PDMS.common.ErrorCode;
import com.sxj.PDMS.common.Result;
import com.sxj.PDMS.constant.JwtClaimsConstant;
import com.sxj.PDMS.exception.BusinessException;
import com.sxj.PDMS.exception.ThrowUtils;
import com.sxj.PDMS.model.dto.admin.AdminLoginRequest;
import com.sxj.PDMS.model.dto.admin.AdminRegisterRequest;
import com.sxj.PDMS.model.dto.admin.AdminUpdatePasswordRequest;
import com.sxj.PDMS.model.entity.Admin;
import com.sxj.PDMS.model.vo.AdminLoginVO;
import com.sxj.PDMS.properties.JwtProperties;
import com.sxj.PDMS.service.AdminService;
import com.sxj.PDMS.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/admin")
@Slf4j
public class AdminController {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private AdminService adminService;
    @Autowired
    private JwtProperties jwtProperties;
    public static final String SALT = "tyutrjxy";

    /**
     * 管理员注册
     */
    @PostMapping("/register")
    public BaseResponse<String> adminRegister(@RequestBody AdminRegisterRequest adminRegisterRequest) {
        if(adminRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空");
        }
        //注册管理员
        String result = adminService.register(adminRegisterRequest);
        return Result.success();
    }

    /**
     * 管理员登录
     *
     * @param adminLoginRequest
     * @param request
     * @return
     */
    @PostMapping("/login")
    public BaseResponse<AdminLoginVO> adminLogin(@RequestBody AdminLoginRequest adminLoginRequest, HttpServletRequest request) {

        log.info("管理员登录：{}", adminLoginRequest);

        String adminId = adminLoginRequest.getAdminId();
        String password = adminLoginRequest.getPassword();

        AdminLoginVO adminLoginVO = adminService.login(adminId, password, request);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.ADMIN_ID, adminId);
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);

        adminLoginVO.setToken(token);


        return Result.success(adminLoginVO);
    }
    /**
     * 用户更新密码
     * @param adminUpdatePasswordRequest
     * @return
     */

    @PutMapping("/modify_password")
    public BaseResponse<Boolean> updateAdminPassword(@RequestBody AdminUpdatePasswordRequest adminUpdatePasswordRequest) {
        if (adminUpdatePasswordRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 1. 校验
        if (StringUtils.isAnyBlank(adminUpdatePasswordRequest.getAdminId(), adminUpdatePasswordRequest.getPassword(),
                adminUpdatePasswordRequest.getNewPassword(), adminUpdatePasswordRequest.getConfirmPassword())){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (adminUpdatePasswordRequest.getPassword().length() < 6){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "旧密码长度不能小于6");
        }
        if (adminUpdatePasswordRequest.getNewPassword().length() < 6||adminUpdatePasswordRequest.getConfirmPassword().length() < 6) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "新密码长度不能小于6");
        }
        // 密码和校验密码相同
        if (!adminUpdatePasswordRequest.getNewPassword().equals(adminUpdatePasswordRequest.getConfirmPassword())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次输入的密码不一致");
        }
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + adminUpdatePasswordRequest.getNewPassword()).getBytes());
        Admin admin = adminService.getById(adminUpdatePasswordRequest.getAdminId());
        admin.setPassword(encryptPassword);
        System.out.println(admin);
        boolean result = adminService.updateById(admin);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        //更新数据后进行缓存更新
        redisTemplate.opsForValue().set("admin:admin_" + adminUpdatePasswordRequest.getAdminId(), admin, 7, TimeUnit.DAYS);
        return Result.success(true);
    }
    /**
     * 获取当前的管理员
     *
     * @return
     */
    @GetMapping("/get_login_admin")
    public BaseResponse<AdminLoginVO> getLoginAdmin() {
        log.info("获取当前登录的登录员");
        AdminLoginVO adminLoginVO = adminService.getLoginAdmin();
        if (adminLoginVO == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }

        return Result.success(adminLoginVO);

    }

    /**
     * 获取管理员信息
     *
     * @param adminId
     * @return
     */
    @GetMapping("/get_info")
    public BaseResponse<Admin> getAdminInfo(String adminId) {
        log.info("获取管理员信息,{}", adminId);

        Object object = redisTemplate.opsForValue().get("admin:admin_" + adminId);
        if (object != null) {
            Admin admin = (Admin) object;
            admin.setPassword(null);
            return Result.success(admin);
        } else {
            Admin admin = adminService.getById(adminId);
            if (admin == null) {
                throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
            } else {
                redisTemplate.opsForValue().set("admin:admin_" + adminId, admin, 7, TimeUnit.DAYS);
                admin.setPassword(null);

                return Result.success(admin);
            }
        }
    }

    /**
     * 退出登录
     *
     * @return
     */
    @GetMapping("/logout_admin")
    public BaseResponse<String> logoutAdmin() {
        log.info("管理员退出登录");

        return Result.success("退出成功");
    }
}
